package com.heubu.mall.service.impl;

import com.heubu.mall.dao.UserMapper;
import com.heubu.mall.enums.ResponseEnum;
import com.heubu.mall.enums.RoleEnum;
import com.heubu.mall.pojo.User;
import com.heubu.mall.service.IUserService;
import com.heubu.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * @Author Wangchuang
 * @Date: 2022/5/5 19:36
 * @Version 1.0
 * @Description:
 */
//注入到IOC容器，勿忘，否则controller报错找不到bean
@Service
public class UserServiceImpl implements IUserService {
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 注册功能
     *
     * @param user
     */
    @Override
    public ResponseVo<User> register(User user) {
        
        //1.username不能重复
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if(countByUsername > 0) {
            return ResponseVo.error(ResponseEnum.USERNAME_EXIST);
        }
        
        //2.email不能重复
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if(countByEmail > 0) {
            return ResponseVo.error(ResponseEnum.EMAIL_EXIST);
        }
    
        user.setRole(RoleEnum.CUSTOMER.getCode());
        
        //3.MD5散列密码
        user.setPassword(DigestUtils.md5DigestAsHex(
                user.getPassword().getBytes(StandardCharsets.UTF_8)
        ));
        
        //4.写入数据库
        int resultCount = userMapper.insertSelective(user);
        if(resultCount == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
        return ResponseVo.success();
    }
    
    /**
     * 登录功能
     *
     * @param username
     * @param password
     */
    @Override
    public ResponseVo<User> login(String username, String password) {
        User user = userMapper.selectByUsername(username);
    
        //1.判断是否存在用户
        if(user == null) {
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        
        //2.判断密码是否正确
        if(!user.getPassword().equalsIgnoreCase(
                DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        
        //3.设置密码为空避免出现密码泄露
        user.setPassword("");
        return ResponseVo.success(user);
    }
}
